//
//  PlayViewController.m
//  YMDemo
//
//  Created by admin on 2022/2/28.
//

#import "PlayViewController.h"
#import <YMLiveKit/YMLiveKit.h>
#import <Masonry/Masonry.h>
#import "UIControl+YYAdd.h"
#import "UIView+YYAdd.h"


@interface PlayViewController ()

@property (nonatomic, strong)  UIButton *closeButton;
@property (nonatomic, strong) YMPlayerView *YmPlayer;
@property (nonatomic, strong) YMLiveSession *session;
@property (nonatomic,strong)UILabel *titleLable;
@property (nonatomic,strong)UIButton *roomNumButton;
@property (nonatomic,strong)UIButton *logoutButton;


@end

@implementation PlayViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    [self requestAccessForAudio];
    [self requestAccessForVideo];
    [self loadVideoNoti];
    [self SetYMPlayer];
//    [self initView];
    

}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![self.YmPlayer.player isPlaying]) {
        
        [self.YmPlayer.player prepareToPlay];
        
    }
    
}
-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
#pragma mark -- Public Method
- (void)requestAccessForVideo {
    __weak typeof(self) _self = self;
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
    case AVAuthorizationStatusNotDetermined: {
        // 许可对话没有出现，发起授权许可
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [_self.session setRunning:YES];
                    });
                }
            }];
        break;
    }
    case AVAuthorizationStatusAuthorized: {
        // 已经开启授权，可继续
        dispatch_async(dispatch_get_main_queue(), ^{
            [_self.session setRunning:YES];
        });
        break;
    }
    case AVAuthorizationStatusDenied:
    case AVAuthorizationStatusRestricted:
        // 用户明确地拒绝授权，或者相机设备无法访问

        break;
    default:
        break;
    }
}

- (void)requestAccessForAudio {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (status) {
    case AVAuthorizationStatusNotDetermined: {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
            }];
        break;
    }
    case AVAuthorizationStatusAuthorized: {
        break;
    }
    case AVAuthorizationStatusDenied:
    case AVAuthorizationStatusRestricted:
        break;
    default:
        break;
    }
}
#pragma mark 初始化播放器
-(void)SetYMPlayer{
    
    self.YmPlayer = [YMPlayerView playerWithURL:self.playUrl];
    [self.view addSubview:self.YmPlayer];
    [self.view addSubview:self.closeButton];

}
#pragma mark 发送弹幕
-(void)sendBarrageAction{
    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setValue:curUser.avatar forKey:@"avatar"];
//    [dic setValue:curUser.nickname forKey:@"nickname"];
//    [dic setValue:self.textView.text forKey:@"chat"];
//    NSMutableArray *array = [NSMutableArray array];
//    [array addObject:dic];
//    NSArray *arrayMessage = [HomeworkModel mj_objectArrayWithKeyValuesArray:array];
//    [self.barrageMessageView addMessage:arrayMessage];
//    self.textView.text = @"";
}
#pragma mark 退出直播
-(void)logoutAction{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    if (![self.YmPlayer.player isPlaying]) {
        
        [self.YmPlayer.player play];
       
    }else {

        [self.YmPlayer.player pause];

    }
}

#pragma mark - 加载完成的方法
-(void)seekCompletedEvent:(NSNotification*)notification{
    
    NSLog(@"视频加载完成....");
}

#pragma mark - 视频播放器状态改变
- (void)moviePlayBackStateDidChange:(NSNotification*)notification
{
    NSInteger playbackState = self.YmPlayer.player.playbackState;

    switch (playbackState) {
        case IJKMPMoviePlaybackStateStopped:
            NSLog(@"播放器的播放状态变了，现在是停止状态:%ld",playbackState);
            break;
        case IJKMPMoviePlaybackStatePlaying:
            NSLog(@"播放器的播放状态变了，现在是播放状态:%ld",playbackState);
            break;
        case IJKMPMoviePlaybackStatePaused:
            NSLog(@"播放器的播放状态变了，现在是暂停状态:%ld",playbackState);
            break;
        case IJKMPMoviePlaybackStateInterrupted:
            NSLog(@"播放器的播放状态变了，现在是中断状态:%ld",playbackState);
            break;
        case IJKMPMoviePlaybackStateSeekingForward:
            NSLog(@"播放器的播放状态变了，现在是向前拖动状态:%ld",playbackState);
            break;
        case IJKMPMoviePlaybackStateSeekingBackward:
            NSLog(@"播放器的播放状态变了，现在是向后拖动状态：%ld",playbackState);
            break;
        default:
            NSLog(@"播放器的播放状态变了，现在是未知状态：%ld",playbackState);
            break;
    }
}


#pragma mark - 播放状态改变
- (void)moviePlayBackFinish:(NSNotification*)notification
{
    int reason = [[[notification userInfo]valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];

    switch (reason) {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"播放状态改变了:播放完毕的状态：%d",reason);
            break;
        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"播放状态改变了:退出状态：%d",reason);
            break;
        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"播放状态改变了:播放错误状态：%d",reason);
            break;
        default:
            break;
    }
}


#pragma mark - 更新加载状态
- (void)loadStateDidChange:(NSNotification*)notification
{
    IJKMPMovieLoadState loadState = self.YmPlayer.player.loadState;
    switch (loadState) {
        case IJKMPMovieLoadStatePlayable:
            NSLog(@"==========加载状态:缓存数据足够开始播放，但是视频并没有缓存完全");
            break;
        case IJKMPMovieLoadStateUnknown:
            NSLog(@"==========加载状态:状态");
            break;
        case IJKMPMovieLoadStatePlaythroughOK:
            NSLog(@"==========加载状态:缓存完成，可播放");
            break;
        case IJKMPMovieLoadStateStalled:
            NSLog(@"==========加载状态:缓存停止，播放停止");
            break;

        default:
            break;
    }
}

#pragma mark - IJKFFMoviePlayerController播放器通知
- (void)loadVideoNoti{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadStateDidChange:) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:self.YmPlayer.player];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackFinish:) name:IJKMPMoviePlayerPlaybackDidFinishNotification object:self.YmPlayer.player];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackStateDidChange:) name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:self.YmPlayer.player];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(seekCompletedEvent:) name:IJKMPMoviePlayerDidSeekCompleteNotification object:self.YmPlayer.player];
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton new];
        _closeButton.size = CGSizeMake(44, 44);
        _closeButton.left = self.view.size.width - 10 - _closeButton.width;
        _closeButton.top = 20;
        [_closeButton setImage:[UIImage imageNamed:@"close_preview"] forState:UIControlStateNormal];
        _closeButton.exclusiveTouch = YES;
        __weak typeof(self) weakify = self;
        [_closeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {

            [weakify.navigationController popViewControllerAnimated:YES];
            [weakify.YmPlayer stopPlay];
            
        }];
    }
    return _closeButton;
}


-(UILabel *)titleLable{
    
    if (_titleLable == nil) {
        
        _titleLable = [[UILabel alloc]init];
        _titleLable.textColor = [UIColor whiteColor];
        _titleLable.font = [UIFont systemFontOfSize:15];
        _titleLable.numberOfLines = 0;
        _titleLable.text = @"英语初级语法讲解";
        
    }
    return _titleLable;
    
}
   
-(UIButton *)roomNumButton{
    
    if (_roomNumButton == nil) {
        
        _roomNumButton = [[UIButton alloc]init];
        _roomNumButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
        _roomNumButton.layer.cornerRadius = 16;
        [_roomNumButton setTitle:@"14人参与" forState:UIControlStateNormal];
        [_roomNumButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _roomNumButton.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    
        
    }
    
    return _roomNumButton;
}

-(UIButton *)logoutButton{
    
    if (_logoutButton == nil) {
        
        _logoutButton = [[UIButton alloc]init];
        [_logoutButton setImage:[UIImage imageNamed:@"Live_Stop"] forState:UIControlStateNormal];
        [_logoutButton addTarget:self action:@selector(logoutAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _logoutButton;
}

@end


